package com.sxau.software_educational_system_backend.service.impl;


import com.aliyun.oss.model.OSSObjectSummary;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxau.software_educational_system_backend.domain.entity.File;
import com.sxau.software_educational_system_backend.domain.req.ReqSaveFileDTO;
import com.sxau.software_educational_system_backend.domain.res.ResFileVO;
import com.sxau.software_educational_system_backend.mapper.FileMapper;
import com.sxau.software_educational_system_backend.service.FileService;
import com.sxau.software_educational_system_backend.utils.AliOssUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
* @author mi
* @description 针对表【file】的数据库操作Service实现
* @createDate 2025-06-01 17:04:20
*/
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
    implements FileService {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Override
    public boolean saveFile(ReqSaveFileDTO dto) {
        File file = new File();
        BeanUtils.copyProperties(dto, file);
        boolean save = this.save(file);
        return save;
    }

    @Override
    public List<OSSObjectSummary> listOssFiles() {
        return aliOssUtil.listFiles();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteFile(Long id) {
        File file = this.getById(id);
        if (file == null) {
            return false;
        }

        boolean removeById = this.removeById(id);
        boolean deleteFile = aliOssUtil.deleteFile(file.getDownloadUrl());
        if (!removeById && !deleteFile) {
            return false;
        }
        return true;
    }

    @Override
    public List<ResFileVO> listFiles() {
        List<File> list = this.list();
        ArrayList<ResFileVO> resFileVOS = new ArrayList<>();
        for (File file : list) {
            ResFileVO resFileVO = new ResFileVO();
            BeanUtils.copyProperties(file, resFileVO);
            resFileVOS.add(resFileVO);
        }
        return resFileVOS;
    }

}




